﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WiiGeeTest
{
  public partial class AccelerometerBar : UserControl
  {
    List<double[]> m_accelValues = new List<double[]>();
    Pen xPen = new Pen(Color.Red);
    Pen yPen = new Pen(Color.Green);
    Pen zPen = new Pen(Color.Blue);
    bool m_refreshRunning = false;
    public int AutoRefreshRateMs
    {
      set;
      get;
    }

    public AccelerometerBar()
    {
      InitializeComponent();
      AutoRefreshRateMs = 30;
    }

    public void AddValue(double _x, double _y, double _z)
    {
      m_accelValues.Add(new double[3] { _x, _y, _z });
      if (m_accelValues.Count > this.Width)
      {
        m_accelValues.RemoveAt(0);
      }
    }

    public bool AutoRefresh
    {
      set
      {
        if (value)
        {
          StartRefresh();
        }
        else
        {
          m_refreshRunning = false;
        }
      }
      get
      {
        return m_refreshRunning;
      }
    }

    private void StartRefresh()
    {
      if (!m_refreshRunning)
      {
        new Thread(new ThreadStart(DoRefresh)).Start();
      }
    }

    private void StopRefresh()
    {
      m_refreshRunning = false;
    }

    private void DoRefresh()
    {
      m_refreshRunning = true;
      while (m_refreshRunning && this.ParentForm != null)
      {
        this.Invalidate();
        Thread.Sleep(AutoRefreshRateMs);
      }
      m_refreshRunning = false;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
      int mult = this.Height/6;
      int start = this.Height/2;
      for (int i = 0; i < m_accelValues.Count - 1; i++)
      {
        //x
        e.Graphics.DrawLine(xPen, i, this.Height - start - (int)(m_accelValues[i][0] * mult), 
                                  i + 1, this.Height - start - (int)(m_accelValues[i + 1][0] * mult));

        //y
        e.Graphics.DrawLine(yPen, i, this.Height - start - (int)(m_accelValues[i][1] * mult),
                          i + 1, this.Height - start - (int)(m_accelValues[i + 1][1] * mult));

        //z
        e.Graphics.DrawLine(zPen, i, this.Height - start - (int)(m_accelValues[i][2] * mult),
                          i + 1, this.Height - start - (int)(m_accelValues[i + 1][2] * mult));
      }

      base.OnPaint(e);
    }

    private void AccelerometerBar_Load(object sender, EventArgs e)
    {

    }

    private void AccelerometerBar_VisibleChanged(object sender, EventArgs e)
    {
      if (this.Visible)
      {
        StartRefresh();
      }
      else
      {
        StopRefresh();
      }
    }

  }
}
